<?php

declare(strict_types=1);

namespace app\api\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class MobileCode extends Model
{
    //


    //保存
    public static function saveCode($model)
    {
        $code = self::where(['user_id' => $model['user_id'], 'mobile' => $model['mobile']])->order('id desc')->find();
        if ($code) {
            $flag = self::checkTime(time(), $code->create_time);
            if ($flag) {
                $str_code = $code->code;
            } else {
                $str_code = self::insertCode($model);
            }
        } else {
            $str_code = self::insertCode($model);
        }
        return $str_code;
    }

    //入库
    public static function insertCode($data)
    {
        self::create($data);
        $str_code = $data['code'];
        return $str_code;
    }


    // 验证验证码时间是否过期
    public static function checkTime($nowTimeStr, $smsCodeTimeStr)
    {
        $smsCodeTime = strtotime($smsCodeTimeStr);
        $period = $nowTimeStr - $smsCodeTime;
        if (intval($period) < (5 * 60)) { //5分钟之内
            return true;
        } else {
            return false; //已超过5分钟
        }
    }


    //验证验证码是否正确
    public static function checkCode($user_id,$mobile,$code) {
  
        $code = self::where(['user_id' => $user_id, 'mobile' => $mobile,'code'=>$code])->order('id desc')->find();
        if ($code) {
            $flag = self::checkTime(time(), $code->create_time);
            if($flag){
                return 1; //正确
            }else{
                return 2; //验证码过期
            }
        }else{
            return 0; //验证码不存在
        }
    }
}
